﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.Web.UI;

namespace TST.SharePointObjects.ContentWebParts
{
    // Tag Cloud based on the tag cloud web part in the Community Kit for SharePoint
    // http://www.codeplex.com/CKS
    [Serializable()]
    public class TagList
    {
        private List<Tag> _tags;
        private string _pageUrl;

        public TagList(string pageUrl)
        {
            _tags = new List<Tag>();
            string url = pageUrl;
            if (url.IndexOf("?") > 0)
            {
                url = url.Substring(0, url.IndexOf("?"));
            }
            _pageUrl = url;
        }

        public List<Tag> Tags
        {
            get { return _tags; }
        }

        public string PageUrl
        {
            get
            {
                return _pageUrl;
            }
        }

        public Tag GetTagByName(string name)
        {
            if (string.IsNullOrEmpty(name))
                return null;
            foreach (Tag tag in Tags)
            {
                if (string.Compare(tag.Name, name, true)==0)
                {
                    return tag;
                }
            }
            return null;
        }

        [XmlIgnore()]
        internal int MaxCount
        {
            get
            {
                int result = 0;
                foreach (Tag tag in Tags)
                {
                    if (tag.Count > result)
                    {
                        result = tag.Count;
                    }
                }
                return result;
            }
        }

        internal void RegisterTag(string text, string value)
        {
            if (GetTagByName(text) == null)
            {
                Tags.Add(new Tag(text, 1, value));
            }
            else
            {
                GetTagByName(text).Count++;
            }
        }

        internal void Sort()
        {
            _tags.Sort();
        }
    }
}
